<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      button {
        height: 50px;
        width: 200px;
      }
    </style>
  </head>
  <body>
    <div>
      <button id="debounce">debounce</button>
      <button id="throttle1">throttle1</button>
      <button id="throttle2">throttle2(时间戳)</button>
    </div>
    <script>
      // 防抖
      function debounce(fn, delay) {
        var timer
        return function () {
          var _this = this
          var args = arguments
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(() => {
            fn.apply(_this, arguments)
          }, delay)
        }
      }

      function testDebouncd(e, content) {
        console.log(e, content)
      }

      var testDebouncdFn = debounce(testDebouncd, 1000)
      document
        .getElementById('debounce')
        .addEventListener('click', (e) => testDebouncdFn(e, 'debounce'))

      // 节流
      function throttle1(fn, delay) {
        var timer
        return function () {
          var _this = this
          var args = arguments
          if (timer) {
            return
          }
          timer = setTimeout(() => {
            fn.apply(_this, args)
            timer = null
          }, delay)
        }
      }

      function throttle2(fn, delay) {
        var prev = 0
        return function () {
          var _this = this
          var args = arguments
          var now = new Date()
          if (now - prev >= delay) {
            fn.apply(_this, args)
            prev = now
          }
        }
      }

      function testThrottle(e, content) {
        console.log(e, content)
      }

      var testThrottleFn = throttle1(testThrottle, 1000)
      document
        .getElementById('throttle1')
        .addEventListener('click', (e) => testThrottleFn(e, 'throttle'))

      var testThrottleFn1 = throttle2(testThrottle, 1000)
      document
        .getElementById('throttle2')
        .addEventListener('click', (e) => testThrottleFn1(e, 'throttle'))
    </script>
  </body>
</html>
